#include "ADUBrick.h"

BrickSprite* BrickSprite::create(const std::string& filename) {
    BrickSprite *sprite = new (std::nothrow) BrickSprite();
    if (sprite && sprite->initWithFile(filename))
    {
        sprite->autorelease();
        return sprite;
    }
    CC_SAFE_DELETE(sprite);
    return nullptr;    
}

BrickSprite* BrickSprite::createWithTexture(Texture2D *texture, const Rect& rect, bool rotated)
{
    BrickSprite *sprite = new (std::nothrow) BrickSprite();
    if (sprite && sprite->initWithTexture(texture, rect, rotated))
    {
        sprite->autorelease();
        return sprite;
    }
    CC_SAFE_DELETE(sprite);
    return nullptr;
}

BrickSprite* BrickSprite::create(int type) {
    BrickSprite* sprite = NULL;
    Texture2D* texture = TextureCache::sharedTextureCache()->addImage("wall.png");
    Texture2D::TexParams tp = {GL_LINEAR,GL_LINEAR,GL_REPEAT, GL_REPEAT};
    texture->setTexParameters(&tp);
    auto winSize = Director::getInstance()->getWinSize();
	auto brickWidth = 0.0;
	auto brickHeight = winSize.height/25;
	if(type == BRICK_TYPE_5) {
		brickWidth = winSize.width/5;
	} else {
		brickWidth = winSize.width/3;
	}
	sprite = BrickSprite::createWithTexture(texture,CCRectMake(0,0,brickWidth,brickHeight),true);
    
    sprite->setType(type);
    switch(type) 
    {
        case BRICK_TYPE_1:
            sprite->setAction(BRICK_TYPE_1);
            break;
        case BRICK_TYPE_2:
            break;
        case BRICK_TYPE_3:
            break;
        case BRICK_TYPE_4:
            break;
        default:
            break;
    }
    return sprite;
}

void BrickSprite::setAction(int type) {

    switch(type)
    {
        case BRICK_TYPE_1:
            _action = RotateBy::create(2.0f,360);
            break;
        case BRICK_TYPE_2:
            
            break;
        case BRICK_TYPE_3:
            break;
        case BRICK_TYPE_4:
            break;
        default:
            break;
    }
}


void BrickSprite::update(float dt) {
    float s = _speed * dt;
    float curX = this->getPositionX();
    float curY = this->getPositionY();

	if(curY < 0) {
		GameManager::getInstance()->increaseScore();
	}

	
    if(curY < -this->getContentSize().height) {
        this->setPositionY(curY + _totalHeight);
        curY = this->getPositionY();
    }
    MoveTo* moveTo = MoveTo::create(dt,Vec2(curX, curY - s));
    this->runAction(moveTo);

	
	
    //this->setPosition(curX, curY - s);
    //log("Y=%s",curY);
    
}
